import traceback

import arrow
from pymongo import MongoClient, UpdateOne

from conf.settings import CLOUDMONITOR_MONGODB, DATE_FMT
from utility.utils import rollback, backup
from utility.log import logger

collection_tuple = ('packages', 'charges')
# db = MongoClient(host='localhost', port=27017)['cloudmonitor']
db = MongoClient(CLOUDMONITOR_MONGODB)['cloudmonitor']

arrow_now = arrow.utcnow()


def main():
    try:
        backup(collection_tuple, logger, db, arrow_now)

        addition_update_list = []
        for addition in db['packages'].find({'chargeType': 'additionPackage'}):
            _temp_dict = {}
            for k, v in addition['limit'].items():
                if v.get('limitType') == 'frequency':
                    _temp_dict[f'limit.{k}.total'] = 0
            addition_update_list.append(UpdateOne({'_id': addition['_id']}, {'$set': _temp_dict}))

        db['charges'].update_many(
            {'chargeType': 'additionPackage', 'limitType': 'frequency'},
            {'$set': {'isDelete': True, 'updateTime': arrow_now.datetime}}
        )

        if addition_update_list:
            db['packages'].bulk_write(addition_update_list)

    except Exception as e:
        rollback(collection_tuple, logger, db, arrow_now)
        logger.exception(e)
        traceback.print_exc()


if __name__ == '__main__':
    main()
